// 输入框修复工具
// 解决uni-app中输入框无法输入的问题

export const inputFix = {
	// 初始化输入框修复
	init() {
		// 在页面加载时执行修复
		this.fixInputStyles()
		this.bindInputEvents()
	},

	// 修复输入框样式
	fixInputStyles() {
		// 动态添加样式
		const style = document.createElement('style')
		style.textContent = `
			/* 输入框修复样式 */
			input, textarea {
				background-color: #fff !important;
				color: #333 !important;
				-webkit-user-select: text !important;
				user-select: text !important;
				-webkit-appearance: none;
				appearance: none;
				-webkit-touch-callout: default;
				-webkit-tap-highlight-color: transparent;
				caret-color: #667eea;
				z-index: 1;
				position: relative;
			}
			
			input:focus, textarea:focus {
				background-color: #fff !important;
				color: #333 !important;
				outline: none;
				-webkit-appearance: none;
				appearance: none;
			}
			
			/* 修复iOS Safari问题 */
			@supports (-webkit-touch-callout: none) {
				input, textarea {
					font-size: 16px;
					background-color: #fff !important;
					color: #333 !important;
				}
			}
		`
		document.head.appendChild(style)
	},

	// 绑定输入框事件
	bindInputEvents() {
		// 监听输入框聚焦事件
		document.addEventListener('focusin', (e) => {
			if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
				this.ensureInputVisible(e.target)
			}
		})

		// 监听输入框失焦事件
		document.addEventListener('focusout', (e) => {
			if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
				this.resetInputStyles(e.target)
			}
		})
	},

	// 确保输入框可见
	ensureInputVisible(input) {
		// 设置输入框样式
		input.style.backgroundColor = '#fff'
		input.style.color = '#333'
		input.style.zIndex = '999'
		input.style.position = 'relative'
		
		// 滚动到输入框位置
		setTimeout(() => {
			input.scrollIntoView({ behavior: 'smooth', block: 'center' })
		}, 100)
	},

	// 重置输入框样式
	resetInputStyles(input) {
		input.style.zIndex = '1'
	},

	// 修复特定输入框
	fixInput(input) {
		if (!input) return
		
		// 设置基本属性
		input.style.backgroundColor = '#fff'
		input.style.color = '#333'
		input.style.webkitUserSelect = 'text'
		input.style.userSelect = 'text'
		input.style.webkitAppearance = 'none'
		input.style.appearance = 'none'
		input.style.caretColor = '#667eea'
		input.style.zIndex = '1'
		input.style.position = 'relative'
		
		// 添加事件监听
		input.addEventListener('focus', () => {
			this.ensureInputVisible(input)
		})
		
		input.addEventListener('blur', () => {
			this.resetInputStyles(input)
		})
	},

	// 修复页面中所有输入框
	fixAllInputs() {
		const inputs = document.querySelectorAll('input, textarea')
		inputs.forEach(input => {
			this.fixInput(input)
		})
	}
}

// 导出默认实例
export default inputFix
